<template>
  <view class="container">
    <cu-custom bgColor="bg-gradual-orange" :isBack="true">
      <template v-slot:content>提交订单</template>
    </cu-custom>

    <view class="main-content">
      <view class="address-section card">
        <view class="title">选择收货地址</view>
        <view class="address-info" @click="openAddressModal">
          <view class="detail" v-if="address.client">
            <view class="name-phone">
              <text class="name">{{ address.client }}</text>
              <text>{{ address.clientPhone }}</text>
            </view>
            <view class="location text-gray">{{ address.address }}</view>
          </view>
          <view class="detail" v-else>
            <view class="text-gray">请选择收货地址</view>
          </view>
          <text class="cuIcon-right"></text>
        </view>
      </view>

      <picker
        mode="multiSelector"
        :value="pickerIndices"
        :range="deliveryOptions"
        range-key="text"
        @change="onDeliveryTimeChange"
        @columnchange="onDeliveryColumnChange"
        @click="prepareDeliveryOptions"
      >
        <view class="delivery-section card">
          <view class="row">
            <text>{{
              selectedDeliveryInfo.type === "now" ? "立即送出" : "预约送达"
            }}</text>
            <view>
              <text class="text-blue">{{ deliveryTimeText }}</text>
              <text class="cuIcon-right"></text>
            </view>
          </view>
        </view>
      </picker>

      <view class="goods-section card">
        <view class="shop-name">{{ merchantName }}</view>
        <view class="goods-list">
          <view class="goods-item" v-for="(item, key) in cart" :key="key">
            <image :src="item.goods.img" class="goods-img"></image>
            <view class="goods-detail">
              <view class="name">{{
                getComboInfo(item, "comDescription") || item.goods.name
              }}</view>
              <view class="spec text-sm text-gray">{{
                getComboInfo(item, "specValues")
              }}</view>
            </view>
            <view class="price-quantity">
              <view class="price"
                >¥{{ getComboInfo(item, "comPrice") || item.goods.price }}</view
              >
              <view class="quantity text-sm">x{{ item.quantity }}</view>
            </view>
          </view>
        </view>

        <view class="fee-row">
          <text>打包费</text>
          <text>¥{{ packingFee }}</text>
        </view>
        <view class="fee-row">
          <text>配送费</text>
          <text>¥{{ deliveryFee }}</text>
        </view>

        <view class="fee-row" @click="openCouponModal('store')">
          <text>店铺活动/券</text>
          <view>
            <text class="text-red coupon-selected-name">
              {{ selectedStoreCoupon?.cardName || storeCouponText }}
            </text>
            <text class="cuIcon-right"></text>
          </view>
        </view>
        <view class="fee-row" @click="openCouponModal('platform')">
          <text>饭团卡券</text>
          <view>
            <text class="text-red coupon-selected-name">
              {{ selectedPlatformCoupon?.cardName || platformCouponText }}
            </text>
            <text class="cuIcon-right"></text>
          </view>
        </view>

        <view class="total-row">
          <text>合计</text>
          <text class="price">¥{{ totalAmount }}</text>
        </view>
      </view>

      <view class="extra-section card">
        <view class="row">
          <text>备注</text>
          <view @click="editRemark">
            <text class="text-gray">{{ remark || "推荐使用无接触配送" }}</text>
            <text class="cuIcon-right"></text>
          </view>
        </view>
        <view class="row">
          <text>餐具数量</text>
          <view @click="selectCutlery">
            <text class="text-gray">{{ cutleryStatus }}</text>
            <text class="cuIcon-right"></text>
          </view>
        </view>
        <view class="row">
          <text>发票</text>
          <text class="text-gray">请联系商家提供</text>
        </view>
      </view>
    </view>

    <!-- 底部支付栏 -->
    <view class="payment-bar">
      <view class="total-price">¥{{ totalAmount }}</view>
      <button
        class="pay-btn cu-btn bg-yellow round"
        @click="showPayModal = true"
      >
        去支付
      </button>
    </view>

    <!-- 支付方式弹窗 -->
    <view
      class="cu-modal"
      :class="showPayModal ? 'show' : ''"
      @tap="showPayModal = false"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white justify-center">
          <view class="content text-bold">选择支付方式</view>
        </view>
        <view class="pay-method-list">
          <view class="pay-method-item" @click="payWithAlipay">
            <image src="/static/images/alipay.png" class="pay-icon" />
            <text class="pay-label">支付宝支付</text>
          </view>
        </view>
        <view class="cu-bar bg-white justify-center">
          <view class="action text-blue" @tap="showPayModal = false">取消</view>
        </view>
      </view>
    </view>

    <!-- 地址选择弹窗 -->
    <view
      class="cu-modal address-selector-modal"
      :class="showAddressModal ? 'show' : ''"
      @tap="closeAddressModal"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white justify-center">
          <view class="content text-bold">选择收货地址</view>
        </view>
        <view class="address-list-modal">
          <view
            class="address-item-modal"
            v-for="item in addressList"
            :key="item.addressId"
            @click="onAddressSelect(item)"
          >
            <view class="info">
              <view class="name-phone">
                <text class="cuIcon-user text-orange"></text>
                <text class="name">姓名：{{ item.client }}</text>
                <text class="phone">电话：{{ item.clientPhone }}</text>
              </view>
              <view class="location">
                <text class="cuIcon-location text-grey"></text>
                <text class="address-text">收货地址：{{ item.address }}</text>
              </view>
            </view>
            <text
              class="cuIcon-check text-orange"
              v-if="item.addressId === address.addressId"
            ></text>
          </view>
          <view v-if="!addressList.length" class="text-center padding text-gray"
            >暂无收货地址</view
          >
        </view>
        <view class="cu-bar bg-white justify-center">
          <view class="action text-blue" @tap="closeAddressModal">关闭</view>
        </view>
      </view>
    </view>

    <!-- 备注弹窗 -->
    <view
      class="cu-modal"
      :class="showRemarkModal ? 'show' : ''"
      @tap="cancelRemark"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white justify-center">
          <view class="content text-bold">填写备注</view>
        </view>
        <view class="padding-xl">
          <textarea
            v-model="tempRemark"
            class="remark-textarea"
            placeholder="请输入备注信息，如口味、偏好等"
            maxlength="100"
          ></textarea>
        </view>
        <view class="cu-bar bg-white">
          <view class="action margin-0 flex-sub text-gray" @tap="cancelRemark"
            >取消</view
          >
          <view
            class="action margin-0 flex-sub text-green solid-left"
            @tap="confirmRemark"
            >确定</view
          >
        </view>
      </view>
    </view>

    <!-- 餐具数量选择弹窗 -->
    <view
      class="cu-modal bottom-modal"
      :class="showCutleryModal ? 'show' : ''"
      @tap="closeCutleryModal"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white">
          <view class="action text-gray" @tap="closeCutleryModal">取消</view>
          <view class="content text-bold">选择餐具数量</view>
        </view>
        <view class="cutlery-options">
          <view
            v-for="item in cutleryOptions"
            :key="item"
            class="option-item"
            :class="{ selected: cutleryStatus === item }"
            @click="onCutlerySelect(item)"
          >
            {{ item }}
            <text v-if="cutleryStatus === item" class="cuIcon-check"></text>
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <view
      class="cu-modal bottom-modal"
      :class="showCouponModal ? 'show' : ''"
      @tap="closeCouponModal"
    >
      <view class="cu-dialog" @tap.stop>
        <view class="cu-bar bg-white">
          <view class="action text-gray" @tap="closeCouponModal">关闭</view>
          <view class="content text-bold">{{
            currentCouponType === "store" ? "选择店铺券" : "选择平台券"
          }}</view>
        </view>
        <view class="coupon-options scrollable-coupons">
          <view class="option-item" @click="onCouponSelect(null)">
            不使用优惠券
          </view>
          <view
            v-for="item in couponListForModal"
            :key="item.cardId"
            class="coupon-card"
            :class="{
              selected: isCouponSelected(item),
              disabled: !isCouponUsable(item),
            }"
            @click="isCouponUsable(item) && onCouponSelect(item)"
          >
            <!-- 左侧色条和icon -->
            <view class="coupon-bar">
              <text class="cuIcon-ticket"></text>
            </view>
            <!-- 主要内容 -->
            <view class="coupon-content">
              <view class="coupon-header">
                <text class="coupon-amount">¥{{ item.cardPrice }}</text>
                <text class="coupon-type">{{
                  item.merId == 0 ? "平台券" : "店铺券"
                }}</text>
              </view>
              <view class="coupon-name">{{ item.cardName }}</view>
              <view class="coupon-expire">有效期：{{ item.expireTime }}</view>
              <view v-if="!isCouponUsable(item)" class="coupon-reason"
                >未满足使用条件</view
              >
            </view>
            <!-- 选中icon -->
            <view class="coupon-check">
              <text
                v-if="isCouponSelected(item)"
                class="cuIcon-check selected-icon"
              ></text>
            </view>
          </view>
          <view v-if="!couponListForModal.length" class="empty-coupon-tip">
            暂无可用优惠券
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get, post } from "@/utils/request.js";

const cart = ref({});
const merchantName = ref("");
const packingFee = ref(0); // 打包费
const deliveryFee = ref(0); // 配送费
const remark = ref("");
const cutleryStatus = ref("无需餐具");
const showPayModal = ref(false);
const showAddressModal = ref(false);
const addressList = ref([]);

// 地址信息
const address = ref({});

// --- 优惠券逻辑 ---
const storeCoupons = ref([]);
const platformCoupons = ref([]);
const selectedStoreCoupon = ref(null);
const selectedPlatformCoupon = ref(null);
const showCouponModal = ref(false);
const currentCouponType = ref("store");

// 动态计算用于弹窗的优惠券列表
const couponListForModal = computed(() => {
  return currentCouponType.value === "store"
    ? storeCoupons.value
    : platformCoupons.value;
});

// 计算属性，用于显示店铺券文本
const storeCouponText = computed(() => {
  if (selectedStoreCoupon.value) {
    return `-¥${selectedStoreCoupon.value.amount}`;
  }
  return storeCoupons.value.length > 0 ? "请选择" : "无可用";
});

// 计算属性，用于显示平台券文本
const platformCouponText = computed(() => {
  if (selectedPlatformCoupon.value) {
    return `-¥${selectedPlatformCoupon.value.amount}`;
  }
  return platformCoupons.value.length > 0 ? "请选择" : "无可用";
});

// 判断优惠券是否被选中
const isCouponSelected = (coupon) => {
  if (!coupon) return false;
  const selectedCoupon =
    currentCouponType.value === "store"
      ? selectedStoreCoupon.value
      : selectedPlatformCoupon.value;
  return selectedCoupon && selectedCoupon.id === coupon.id;
};

// 判断当前券是否可用
const isCouponUsable = (coupon) => {
  // 订单合计金额（未减去优惠券前）
  const baseTotal = goodsTotal.value + packingFee.value + deliveryFee.value;
  return baseTotal >= Number(coupon.condition || 0);
};

// 获取优惠券列表
const fetchCoupons = async () => {
  const user = JSON.parse(uni.getStorageSync("user") || "{}");
  const userId = user?.userId;
  const cartData = uni.getStorageSync("cart_data");
  const merchantId = cartData?.merchantId;
  console.log("fetchCoupons - userId:", userId);
  console.log("fetchCoupons - cartData:", cartData);
  console.log("fetchCoupons - merchantId:", merchantId);
  console.log("fetchCoupons - cartData.merchantId:", cartData?.merchantId);

  if (!userId || !merchantId) {
    console.warn("无法获取优惠券，缺少userId或merchantId");
    return;
  }

  try {
    // 真实接口请求
    const res = await get(
      `/order/getCardByUserIdAndMerchantId?userId=${userId}&merchantId=${merchantId}`
    );
    console.log(res.data.code);
    if (res && res.data && res.data.code === 200) {
      // 过滤未过期的优惠券
      const currentTime = new Date().getTime();
      const validCoupons = res.data.msg.filter((item) => {
        const expireTime = new Date(item.expireTime).getTime();
        return expireTime > currentTime;
      });

      storeCoupons.value = validCoupons.filter(
        (item) => item.merId == merchantId
      );
      platformCoupons.value = validCoupons.filter((item) => item.merId == 0);
      console.log("-----------------------");
      console.log("storeCoupons.value:" + storeCoupons.value);
      console.log("platformCoupons.value:" + platformCoupons);
    }
  } catch (error) {
    console.error("获取优惠券失败:", error);
    uni.showToast({ title: "获取优惠券失败", icon: "none" });
  }
};

const openCouponModal = (type) => {
  currentCouponType.value = type;
  showCouponModal.value = true;
};

const closeCouponModal = () => {
  showCouponModal.value = false;
};

const onCouponSelect = (coupon) => {
  if (coupon && !isCouponUsable(coupon)) {
    uni.showToast({ title: "未满足使用条件", icon: "none" });
    return;
  }
  if (currentCouponType.value === "store") {
    selectedStoreCoupon.value = coupon;
  } else {
    selectedPlatformCoupon.value = coupon;
  }
  closeCouponModal();
};

// --- 备注和餐具逻辑 ---
const showRemarkModal = ref(false);
const tempRemark = ref("");
const showCutleryModal = ref(false);
const cutleryOptions = [
  "无需餐具",
  "需要餐具，商家按量提供",
  ...Array.from({ length: 10 }, (_, i) => `${i + 1}份`),
  "10份以上",
];

const editRemark = () => {
  tempRemark.value = remark.value;
  showRemarkModal.value = true;
};

const cancelRemark = () => {
  showRemarkModal.value = false;
};

const confirmRemark = () => {
  remark.value = tempRemark.value;
  showRemarkModal.value = false;
};

const selectCutlery = () => {
  showCutleryModal.value = true;
};

const closeCutleryModal = () => {
  showCutleryModal.value = false;
};

const onCutlerySelect = (item) => {
  cutleryStatus.value = item;
  closeCutleryModal();
};

// --- 配送时间选择逻辑 ---
const pickerIndices = ref([0, 0]);
const deliveryOptions = ref([[], []]);
const selectedDeliveryInfo = ref({ type: "now", date: "", time: "" });

// 格式化送达时间文本
const deliveryTimeText = computed(() => {
  if (selectedDeliveryInfo.value.type === "now") {
    const now = new Date();
    const startTime = new Date(now.getTime() + 30 * 60 * 1000);
    const endTime = new Date(now.getTime() + 45 * 60 * 1000);
    const format = (d) =>
      `${d.getHours().toString().padStart(2, "0")}:${d
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    return `预计${format(startTime)}-${format(endTime)}送达`;
  }
  return `${selectedDeliveryInfo.value.date.text} ${selectedDeliveryInfo.value.time}`;
});

// 生成日期列
const generateDateColumn = () => {
  const dates = [];
  const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  for (let i = 0; i < 7; i++) {
    const d = new Date();
    d.setDate(d.getDate() + i);
    let text;
    if (i === 0) text = "今天";
    else if (i === 1) text = "明天";
    else
      text = `${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
        .getDate()
        .toString()
        .padStart(2, "0")}`;

    dates.push({
      text: `${text} (${week[d.getDay()]})`,
      value: d,
    });
  }
  return dates;
};

// 生成时间列
const generateTimeSlots = (date) => {
  const slots = [];
  const now = new Date();
  const isToday = date.toDateString() === now.toDateString();

  if (isToday) {
    slots.push({ text: "尽快送达" });
  }

  let startHour = 0;
  let startMinute = 0;

  if (isToday) {
    const earliestTime = new Date(now.getTime() + 30 * 60 * 1000);
    startHour = earliestTime.getHours();
    // 向上取整到下一个20分钟的倍数
    startMinute = Math.ceil(earliestTime.getMinutes() / 20) * 20;
    if (startMinute >= 60) {
      startHour++;
      startMinute = 0;
    }
  }

  const startTime = new Date(date);
  startTime.setHours(startHour, startMinute, 0, 0);

  while (startTime.getDate() === date.getDate() && startTime.getHours() < 24) {
    const endTime = new Date(startTime.getTime() + 20 * 60 * 1000);
    const format = (d) =>
      `${d.getHours().toString().padStart(2, "0")}:${d
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    slots.push({ text: `${format(startTime)}-${format(endTime)}` });
    startTime.setTime(endTime.getTime());
  }
  return slots;
};

// 准备并更新选择器数据
const prepareDeliveryOptions = () => {
  const dateCol = generateDateColumn();
  // 根据当前选中的日期，或者默认的第一个日期来生成时间列
  const dateValue =
    deliveryOptions.value[0][pickerIndices.value[0]]?.value || dateCol[0].value;
  const timeCol = generateTimeSlots(dateValue);
  deliveryOptions.value = [dateCol, timeCol];
};

// 确认选择
const onDeliveryTimeChange = (e) => {
  const [dateIndex, timeIndex] = e.detail.value;
  pickerIndices.value = [dateIndex, timeIndex];

  const date = deliveryOptions.value[0][dateIndex];
  const time = deliveryOptions.value[1][timeIndex];

  if (!date || !time) return;

  if (time.text === "尽快送达") {
    selectedDeliveryInfo.value = {
      type: "now",
      date: "",
      time: "",
    };
  } else {
    selectedDeliveryInfo.value = {
      type: "预约",
      date: date,
      time: time.text,
    };
  }
};

// 当列滚动时
const onDeliveryColumnChange = (e) => {
  const { column, value } = e.detail;
  pickerIndices.value[column] = value;

  if (column === 0) {
    // 如果是日期列变化
    const newDate = deliveryOptions.value[0][value].value;
    const newTimeSlots = generateTimeSlots(newDate);
    deliveryOptions.value[1] = newTimeSlots;
    pickerIndices.value[1] = 0; // 重置时间列的索引
  }
};

// 打开地址选择弹窗
const openAddressModal = () => {
  showAddressModal.value = true;
};

// 关闭地址选择弹窗
const closeAddressModal = () => {
  showAddressModal.value = false;
};

// 选择地址
const onAddressSelect = (selected) => {
  address.value = selected;
  closeAddressModal();
};

// 获取地址列表
const fetchAddressList = async () => {
  let user = uni.getStorageSync("user");
  if (typeof user === "string") {
    try {
      user = JSON.parse(user);
    } catch (e) {
      user = {};
    }
  }
  const userId = user?.userId || "";
  if (!userId) {
    uni.showToast({ title: "请先登录", icon: "none" });
    return;
  }

  try {
    const res = await get("/adress/useradressse", { data: { userId } });
    // 根据调试结果，地址列表在 res.data.msg 中
    if (
      res &&
      res.data &&
      res.data.code === 200 &&
      Array.isArray(res.data.msg)
    ) {
      addressList.value = res.data.msg;

      // 默认选择第一个地址
      if (res.data.msg.length > 0) {
        address.value = res.data.msg[0];
      }
    } else {
      addressList.value = [];
    }
  } catch (error) {
    console.error("获取地址列表失败:", error);
    uni.showToast({ title: "获取地址失败", icon: "none" });
  }
};

// 计算预计送达时间
const deliveryTimeRange = computed(() => {
  const formatTime = (date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${hours}:${minutes}`;
  };

  const now = new Date();
  const startTime = new Date(now.getTime() + 30 * 60 * 1000);
  const endTime = new Date(now.getTime() + 45 * 60 * 1000);

  return `预计${formatTime(startTime)}-${formatTime(endTime)}送达`;
});

// 计算商品总价
const goodsTotal = computed(() => {
  return Object.values(cart.value).reduce((sum, item) => {
    const price =
      item.comboInfo && item.comboInfo.length > 0
        ? item.comboInfo[0].comPrice
        : item.goods.price;
    return sum + price * item.quantity;
  }, 0);
});

// 计算订单总金额（商品总价 + 打包费 + 配送费 - 优惠券）
const totalAmount = computed(() => {
  // 订单原始总价
  const baseTotal = goodsTotal.value + packingFee.value + deliveryFee.value;
  // 判断券是否可用
  const storeDiscount =
    selectedStoreCoupon.value && isCouponUsable(selectedStoreCoupon.value)
      ? Number(selectedStoreCoupon.value.cardPrice)
      : 0;
  const platformDiscount =
    selectedPlatformCoupon.value && isCouponUsable(selectedPlatformCoupon.value)
      ? Number(selectedPlatformCoupon.value.cardPrice)
      : 0;
  const finalTotal = baseTotal - storeDiscount - platformDiscount;
  return finalTotal > 0 ? finalTotal.toFixed(2) : "0.00";
});

const getComboInfo = (item, key) => {
  if (item.comboInfo && item.comboInfo.length > 0) {
    return item.comboInfo[0][key];
  }
  return null;
};

const submitOrder = async () => {
  if (!address.value.addressId) {
    uni.showToast({ title: "请选择收货地址", icon: "none" });
    // 返回一个 rejection，以便调用方可以捕获
    return Promise.reject(new Error("请选择收货地址"));
  }

  // 获取userId
  let user = uni.getStorageSync("user");
  if (typeof user === "string") {
    try {
      user = JSON.parse(user);
    } catch (e) {
      user = {};
    }
  }
  const userId = user?.userId || "";
  if (!userId) {
    return Promise.reject(new Error("用户未登录，无法提交订单"));
  }

  // 格式化配送信息，始终发送具体时间范围
  let deliveryInfo = "";
  if (selectedDeliveryInfo.value.type === "now") {
    const now = new Date();
    const startTime = new Date(now.getTime() + 30 * 60 * 1000);
    const endTime = new Date(now.getTime() + 45 * 60 * 1000);
    const format = (d) =>
      `${d.getHours().toString().padStart(2, "0")}:${d
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    deliveryInfo = `预计${format(startTime)}-${format(endTime)}送达`;
  } else {
    deliveryInfo = `${selectedDeliveryInfo.value.date.text} ${selectedDeliveryInfo.value.time}`;
  }

  const params = {
    userId: userId,
    addressId: address.value.addressId,
    deliveryStatus: deliveryInfo,
    packingFee: packingFee.value,
    totalAmount: totalAmount.value,
    remark: remark.value || "推荐使用无接触配送",
    cutleryCount: cutleryStatus.value,
    storeCouponId: selectedStoreCoupon.value?.id || null,
    platformCouponId: selectedPlatformCoupon.value?.id || null,
    items: Object.values(cart.value).map((item) => ({
      good_id: item.goods.id,
      quantity: item.quantity,
      price:
        item.comboInfo && item.comboInfo.length > 0
          ? item.comboInfo[0].comPrice
          : item.goods.price,
      spec: getComboInfo(item, "specValues") || "",
    })),
  };

  try {
    const res = await post("/user/order/submit", params);
    if (res && res.data && res.data.code === 200) {
      // 订单创建成功，返回后端数据（应包含订单ID）
      return res.data;
    } else {
      // 订单创建失败
      throw new Error(res?.data?.msg || "订单提交失败");
    }
  } catch (error) {
    console.error("订单提交失败:", error);
    // 抛出错误，让调用方处理
    throw error;
  }
};

onMounted(() => {
  // 页面加载时准备好初始数据
  prepareDeliveryOptions();
  fetchAddressList(); // 获取地址
  fetchCoupons(); // 获取优惠券
  const cartData = uni.getStorageSync("cart_data");
  if (cartData) {
    cart.value = cartData.cart;
    merchantName.value = cartData.merchantName;
    deliveryFee.value = cartData.deliveryFee || 0;
    packingFee.value = cartData.packingFee || 0;
  }
});

// 支付宝支付
const payWithAlipay = async () => {
  showPayModal.value = false;

  try {
    uni.showLoading({ title: "正在创建订单..." });
    // 1. 先提交订单信息到后端
    const orderResult = await submitOrder();

    // 假设后端成功后返回的数据在 orderResult.data 中，并且包含 orderId
    const orderId = orderResult.data?.orderId;
    if (!orderId) {
      throw new Error("创建订单失败，未获取到订单号");
    }

    // 清空本地购物车缓存，因为订单已创建
    uni.removeStorageSync("cart_data");

    uni.hideLoading();
    uni.showLoading({ title: "正在跳转到支付宝..." });

    // 2. 使用后端返回的订单号去支付
    const amount = totalAmount.value;
    const subject = `订单支付-${orderId}`;
    const url = `/alipay/pay?traceNo=${orderId}&amount=${amount}&subject=${subject}`;

    const res = await get(url); // 只传拼接好的URL

    uni.hideLoading();

    // 检查返回的是否是支付宝的HTML表单
    if (res && typeof res.data === "string" && res.data.includes("<form")) {
      // #ifdef H5
      // 手动提交表单，绕过浏览器安全限制
      const div = document.createElement("div");
      div.style.display = "none"; // 隐藏div
      div.innerHTML = res.data;
      document.body.appendChild(div);

      const form = div.querySelector("form");
      if (form) {
        form.submit();
      } else {
        uni.showToast({ title: "无法找到支付表单", icon: "none" });
      }
      // #endif

      // #ifndef H5
      uni.showModal({
        title: "支付提示",
        content: "请在H5环境下完成支付操作。",
        showCancel: false,
      });
      // #endif
    } else {
      uni.showToast({
        title: (res && res.data && res.data.msg) || "支付请求失败",
        icon: "none",
      });
    }
  } catch (err) {
    uni.hideLoading();
    uni.showToast({
      title: err.message || "操作失败，请稍后重试",
      icon: "none",
    });
  }
};
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  padding-bottom: 120rpx; /* 为底部支付栏留出空间 */
}
.main-content {
  padding-top: 0rpx; /* 增加此区域的顶部间距 */
}
.card {
  background-color: #ffffff;
  border-radius: 16rpx;
  margin: 24rpx;
  padding: 24rpx;
}
.address-section .title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}
.address-section .address-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.delivery-section .row,
.extra-section .row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
}
.goods-section .shop-name {
  font-weight: bold;
  margin-bottom: 20rpx;
}
.goods-item {
  display: flex;
  margin-bottom: 20rpx;
}
.goods-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}
.goods-detail {
  flex: 1;
}
.price-quantity {
  text-align: right;
}
.fee-row,
.total-row {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 0;
}
.total-row .price {
  font-size: 36rpx;
  font-weight: bold;
  color: #e54d42;
}
.payment-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 24rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.payment-bar .total-price {
  font-size: 36rpx;
  font-weight: bold;
  color: #e54d42;
  margin-right: 20rpx;
}
.pay-method-list {
  padding: 40rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.pay-method-item {
  display: flex;
  align-items: center;
  padding: 30rpx 60rpx;
  border-radius: 16rpx;
  background: #f5f7fa;
  margin-bottom: 20rpx;
  cursor: pointer;
}
.pay-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 24rpx;
}
.pay-label {
  font-size: 32rpx;
  color: #222;
}
.address-selector-modal.show {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.address-selector-modal .cu-dialog {
  display: flex;
  flex-direction: column;
  max-height: 75vh;
}
.address-list-modal {
  flex: 1;
  min-height: 0;
  overflow-y: auto;
  padding: 0 20rpx;
}
.address-item-modal {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 10rpx;
  border-bottom: 1px solid #f0f0f0;
}
.address-item-modal .info {
  flex: 1;
  margin-right: 20rpx;
}
.address-item-modal .name-phone {
  display: flex;
  align-items: baseline;
  font-size: 32rpx;
  margin-bottom: 16rpx;
}
.address-item-modal .name-phone .cuIcon-user {
  margin-right: 16rpx;
  font-size: 36rpx;
}
.address-item-modal .name-phone .name {
  font-weight: bold;
  margin-right: 24rpx;
}
.address-item-modal .name-phone .phone {
  color: #666;
  font-size: 30rpx;
}
.address-item-modal .location {
  display: flex;
  align-items: flex-start;
  font-size: 28rpx;
  color: #888;
}
.address-item-modal .location .cuIcon-location {
  margin-right: 16rpx;
  margin-top: 4rpx;
  font-size: 36rpx;
}
.address-item-modal .location .address-text {
  line-height: 1.4;
}
.address-item-modal .cuIcon-check {
  color: #f37b1d;
  font-size: 44rpx;
}
.card {
  background: #fff;
  border-radius: 16rpx;
  margin: 20rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}
.address-section .title {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 20rpx;
}
.address-info {
  display: flex;
  align-items: center;
}
.address-info .detail {
  flex: 1;
}
.address-info .name-phone {
  font-size: 32rpx;
  font-weight: bold;
}
.address-info .name {
  margin-right: 20rpx;
}
.address-info .location {
  margin-top: 10rpx;
}
.remark-textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 30rpx;
  box-sizing: border-box;
  line-height: 1.5;
}
.remark-textarea::placeholder {
  color: #bbb;
}
.cutlery-options {
  max-height: 50vh;
  overflow-y: auto;
}
.option-item {
  padding: 30rpx;
  text-align: center;
  font-size: 32rpx;
  border-bottom: 1px solid #f5f5f5;
  position: relative;
}
.option-item.selected {
  color: #f37b1d;
  font-weight: bold;
}
.option-item .cuIcon-check {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}
.coupon-options {
  max-height: 50vh;
  overflow-y: auto;
}
.empty-coupon-tip {
  text-align: center;
  color: #999;
  padding: 40rpx 0;
}
.coupon-card {
  display: flex;
  align-items: stretch;
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 4rpx 18rpx rgba(255, 193, 7, 0.1);
  margin: 24rpx 0;
  border: 2rpx solid #ffd180;
  transition: box-shadow 0.2s, border 0.2s;
  position: relative;
  overflow: hidden;
  min-height: 120rpx;
  margin-left: 24rpx;
  margin-right: 24rpx;
}
.coupon-card.selected {
  border: 2rpx solid #ff9800;
  box-shadow: 0 8rpx 24rpx rgba(255, 152, 0, 0.18);
}
.coupon-bar {
  width: 32rpx;
  background: linear-gradient(180deg, #ff9800 0%, #ffd180 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 36rpx;
  padding-top: 10rpx;
}
.coupon-content {
  flex: 1;
  padding: 24rpx 20rpx 20rpx 24rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.coupon-header {
  display: flex;
  align-items: baseline;
  gap: 18rpx;
}
.coupon-amount {
  font-size: 54rpx;
  color: #ff9800;
  font-weight: bold;
  line-height: 1.1;
  letter-spacing: 2rpx;
}
.coupon-type {
  font-size: 22rpx;
  color: #fff;
  background: linear-gradient(90deg, #ff9800 0%, #ffd180 100%);
  border-radius: 8rpx;
  padding: 2rpx 16rpx;
  margin-left: 10rpx;
}
.coupon-name {
  font-size: 30rpx;
  color: #333;
  margin: 10rpx 0 4rpx 0;
  font-weight: 500;
}
.coupon-expire {
  font-size: 22rpx;
  color: #888;
}
.coupon-check {
  width: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.selected-icon {
  color: #ff9800;
  font-size: 44rpx;
  transition: transform 0.2s;
  transform: scale(1.2);
}
.coupon-card:active {
  box-shadow: 0 2rpx 8rpx rgba(255, 152, 0, 0.1);
  border-color: #ffb74d;
}
.scrollable-coupons {
  max-height: 50vh;
  overflow-y: auto;
  padding-right: 8rpx;
}
.coupon-selected-name {
  font-weight: bold;
  font-size: 28rpx;
  margin-right: 8rpx;
}
.coupon-card.disabled {
  filter: grayscale(1);
  opacity: 0.6;
  pointer-events: none;
}
.coupon-reason {
  color: #bbb;
  font-size: 22rpx;
  margin-top: 6rpx;
}
</style>
